package top.wilsonlv.jaguar.cloud.auth.arcsoft;

import com.arcsoft.face.ActiveFileInfo;
import com.arcsoft.face.EngineConfiguration;
import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.FunctionConfiguration;
import com.arcsoft.face.enums.DetectMode;
import com.arcsoft.face.enums.DetectOrient;
import com.arcsoft.face.enums.ErrorInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.wilsonlv.jaguar.commons.web.exception.impl.CheckedException;

/**
 * @author lvws
 * @since 2022/1/11
 */
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "jaguar.auth", name = "face-auth-enable", havingValue = "true")
public class ArcFaceConfigurer {

    private final ArcProperties arcProperties;

    @Bean
    public FunctionConfiguration functionConfiguration() {
        //功能配置
        FunctionConfiguration functionConfiguration = new FunctionConfiguration();
        functionConfiguration.setSupportAge(true);
        functionConfiguration.setSupportFace3dAngle(true);
        functionConfiguration.setSupportFaceDetect(true);
        functionConfiguration.setSupportFaceRecognition(true);
        functionConfiguration.setSupportGender(true);
        functionConfiguration.setSupportLiveness(true);
        functionConfiguration.setSupportIRLiveness(true);
        return functionConfiguration;
    }

    @Bean
    public FaceEngine faceEngine(FunctionConfiguration functionConfiguration) {
        FaceEngine faceEngine = new FaceEngine(arcProperties.getDriverDir());

        //激活引擎
        int errorCode = faceEngine.activeOnline(arcProperties.getAppId(), arcProperties.getSdkKey());
        if (errorCode != ErrorInfo.MOK.getValue() && errorCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue()) {
            throw new CheckedException("引擎激活失败");
        }

        errorCode = faceEngine.getActiveFileInfo(new ActiveFileInfo());
        if (errorCode != ErrorInfo.MOK.getValue() && errorCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue()) {
            throw new CheckedException("获取激活文件信息失败");
        }

        //引擎配置
        EngineConfiguration engineConfiguration = new EngineConfiguration();
        engineConfiguration.setDetectMode(DetectMode.ASF_DETECT_MODE_IMAGE);
        engineConfiguration.setDetectFaceOrientPriority(DetectOrient.ASF_OP_ALL_OUT);
        engineConfiguration.setDetectFaceMaxNum(10);
        engineConfiguration.setDetectFaceScaleVal(16);
        engineConfiguration.setFunctionConfiguration(functionConfiguration);

        //初始化引擎
        errorCode = faceEngine.init(engineConfiguration);
        if (errorCode != ErrorInfo.MOK.getValue()) {
            throw new CheckedException("初始化引擎失败");
        }

        faceEngine.setLivenessParam(0.5f, 0.7f);
        return faceEngine;
    }

}
